const mysql = require('mysql');
const bcrypt = require('bcryptjs');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'test'
});

connection.connect((err) => {
    if (err) throw err;
    console.log('Connected to MySQL database');
});

const User = {
    create: (username, password, email, callback) => {
        bcrypt.hash(password, 10, (err, hash) => {
            if (err) return callback(err);
            const query = 'INSERT INTO users (username, password, email) VALUES (?, ?, ?)';
            connection.query(query, [username, hash, email], callback);
        });
    },
    findByUsername: (username, callback) => {
        const query = 'SELECT * FROM users WHERE username = ?';
        connection.query(query, [username], (err, results) => {
            if (err) return callback(err);
            callback(null, results[0]);
        });
    },
    findById: (id, callback) => { // 添加 findById 方法
        const query = 'SELECT * FROM users WHERE id = ?';
        connection.query(query, [id], (err, results) => {
            if (err) return callback(err);
            callback(null, results[0]);
        });
    },
    getAll: (callback) => {
        const query = 'SELECT * FROM users';
        connection.query(query, callback);
    },
    deleteById: (id, callback) => {
        const query = 'DELETE FROM users WHERE id = ?';
        connection.query(query, [id], callback);
    },
    updateById: (id, data, callback) => {
        const query = 'UPDATE users SET ? WHERE id = ?';
        connection.query(query, [data, id], callback);
    }
};

module.exports = User;